import { ref, reactive } from 'vue';
import { isNil, set, unset } from 'lodash';
import type { TableColumn } from '@/common/types/app.js';
import { tableMaxHeightAdjust } from '@/common/const.js';

export const tableColumnDefault: TableColumn = {
    type: 'default',
    align: 'center',
    prop: '',
    label: '',
    isHidden: false,
    order: -1,
    sortable: true,
    formFieldItemType: 'input',
}


export const tableDefaultAttribute = {
    'border': true,
    'highlight-current-row': true,
    'header-cell-style': {
        'background': '#1e78bf',
        'color': '#FFFFFF',
        'font-size': '16px',
        'font-weight': 'bold',
    },
    'style': {
        'width': '100%'
    },
    // 'row-key': 'id',
    rowKey: 'id',
    'table-layout': 'auto'
}

type OrderItem = {
    [columnname: string]: string    //
}

export function useTableHeightInfo(tableRef: any, tableHeight: any) {
    tableHeight.value = window.innerHeight - Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom ) + tableMaxHeightAdjust;
}
export function useTableInfo(onRefresh: () => void) {
    // const tableHeight = computed(() => window.innerHeight - Math.ceil(tableRef.value?.$el.getBoundingClientRect().top) - tableMaxHeightAdjust);
    const currentPage = ref(1);  // 当前页数
    const pageSize = ref(50);  // 每页行数
    const totalnum = ref(0);   // 总行数
    // const tableHeight = ref(0); // 表格高
    const orders = reactive<OrderItem>({});
    // tableHeight.value = window.innerHeight - tableTop;
    // const defaultPageSize = 50; // 默认每页行数

    // 每页行数改变
    const handleSizeChange = (pagesize: number) => {
        currentPage.value = 1;
        pageSize.value = pagesize;
        onRefresh();
    }
    // 当前页改变
    const handleCurrentChange = (curpage: number) => {
        currentPage.value = curpage;
        onRefresh();
    }
    // 排序   
    const handleSortChange = (e: { column: any, prop: any, order: any }) => {
        if (!isNil(e.column?.order)) {
            console.log(e);
            //orders.push({ [e.column?.property]: e.column?.order === 'ascending' ? 'asc' : 'desc' })
            set(orders, e.prop, e.column?.order === 'ascending' ? 'ASC' : 'DESC');
        } else {
            unset(orders, e.prop);
        }
        /* forOwn(orders, (v, k) => {
            tableRef.value.sort(k, v === 'ASC' ? 'ascending' : 'descending');    
        }); */
        currentPage.value = 1;
        onRefresh();
    }
    // 自定义排序函数
    /* const customSortMethod = (a: any, b: any) => {
        console.log('a', a);
        
        // 使用 localeCompare 方法进行排序，确保中文字符正确排序
        return a.chineseField.localeCompare(b.chineseField);
      } */
    return { currentPage, orders, pageSize, totalnum, handleSizeChange, handleCurrentChange, handleSortChange};
}